Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

244
Vistas
How to show chosen option | Material UI Autocomplete

I'm fetching data from an API as an options in Material UI Autocomplete, the options fetched correctly but the problem is when I choose an option and send it back to the API (POST) the option (category) doesn't show as a text it shows as a number (0) as shown in the image below (Mongodb) enter image description here

        import Autocomplete from '@mui/material/Autocomplete';
    import TextField from '@mui/material/TextField';
    
    export default function Write() {
    
    const [categories, setCategories] = useState("");
    
        const handlerSubmit = async (e) => {
            e.preventDefault();
            const newPost = {
                username: user.username,
                title,
                categories,
            } if (file) {

            try {
                
            } catch (err) {

            }
        }
        try {
            const res = await axios.post("/posts", newPost);
            
        } catch (err) {

        }

           }
           
                 useEffect(() => {
            const getCats = async () => {
              const res = await axios.get("/categories");
              setCategories(res.data);
            };
            getCats();
          }, []);
      
      return (
      <div className='write'>
      <form className="writeForm" onSubmit={handlerSubmit}>
                          <input
                        className="writeTitleInput"
                        required
                        type="text"  
                        placeholder="title"  
                        autoFocus={true}
                        onChange={e => setTitle(e.target.value)}>
                        </input>
                        
                                <Autocomplete
                                multiple
                                limitTags={3}
                                id="tags-standard"
                                options={categories}
                                getOptionLabel={option => (option.name ? option.name : "")}
                                onChange={(e) => setCategories(e.target.value)} 
                                renderInput={(params) => (
                                <TextField
                                   {...params}
                                    variant="standard"
                                    label="Multiple values"
                                    placeholder="Choose a Category"
                                />
                                )}
                    />
                    
                    <button className="writeSubmitButton" type="submit">Publish</button>
      </form>
      </div>
    
      )
    }

The question is how to show the chosen option as a string not array?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Per the docs, the signature of onChange for Autocomplete is

function(
  event: React.SyntheticEvent,
  value: T | Array<T>,
  reason: string,
  details?: string) => void

You are expecting the value to be in event, when in fact, it's in value. Modify your onChange callback to something like the following:

onChange={(_, value) => setCategories(value)} 

value may not be in the shape your API expects, so you should try using console.log in the callback to determine its shape and then modify the above appropriately.

value is Array<T> when multiple is set, so you should probably also have your default for categories set to the same type, i.e. an empty array ([]) instead of an empty string ("").

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda